console.log("this is popup");
// 一次性通信
// const redBtn = document.getElementById('redBtn');
// const blueBtn = document.getElementById('blueBtn');
// const greenBtn = document.getElementById('greenBtn');

// redBtn.addEventListener('click', async() => {
//     // 向content script发送消息
//     const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
//     const response = await chrome.tabs.sendMessage(tab.id, {color: "red"});
//     console.log(response);
// });

// blueBtn.addEventListener('click', async() => {
//     const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
//     const response = await chrome.tabs.sendMessage(tab.id, {color: "blue"});
//     console.log(response);
// });

// greenBtn.addEventListener('click', async() => {
//     const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
//     const response = await chrome.tabs.sendMessage(tab.id, {color: "green"});
//     console.log(response);
// });

// 长通信
const jltxBtn = document.getElementById("jltx");
let port = null; // 存储port引用

jltxBtn.addEventListener("click", async () => {
    try {
      await establishConnection();
    } catch (error) {

      console.error('Connection error:', error);
    }
});

const establishConnection = async () => {
  // 首先获取当前活动标签页
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab?.id) {
    throw new Error("No active tab found");
  }
  
  // 如果已存在连接，先断开
  if (port) {
    port.disconnect();
  }
  
  // 建立新连接
  port = chrome.tabs.connect(tab?.id, { name: "连接" });
  
  // 监听连接断开
  port.onDisconnect.addListener(() => {
    console.log("连接已断开");
    port = null;
  });
  
  // 发送初始消息
  port.postMessage({ question: "坤坤你在哪？" });
  
  // 监听消息
  port.onMessage.addListener(function (msg) {
    // 检查连接是否还存在
    if (chrome.runtime.lastError || !port) {
      console.error("Port connection error:", chrome.runtime.lastError);
      return;
    }
    
    console.log("popup收到的消息", msg);
    try {
      if (msg.answer === "你好") {
        port.postMessage({ question: "你是坤坤吗？" });
      } else if (msg.answer === "我是content_script") {
        port.postMessage({ question: "我找坤坤， 坤坤你在哪？" });
      }
    } catch (error) {
      console.error("发送消息失败:", error);
    }
  });
};
